import store from '../store'
import { session } from '../utils/jcore/storage'
import { findNodeDfs } from '../utils/jcore/tree'
import { globalRoutes, staticRoute } from './index'

/**
 * 判断是否为全局或固定路由路由
 * @param {any} route 当前路由
 */
export function fnCurrentRouteType(route) {
  return findNodeDfs(globalRoutes, (node) => node.path == route.path)
}

/**
 * 为路由树添加 menuType
 * @param {*} treeList
 * @returns treeList
 */
export function addMenuType(treeList) {
  findNodeDfs(treeList, (node) => {
    if (node.children && node.children.length) {
      node.menuType = 2
    } else {
      node.menuType = 3
    }
    return false
  })
  return treeList
}

/**
 * 回显侧边栏
 * @param {object} routes
 */
export function showSidebar(routes) {
  let selectRoute = null
  let selectNavName = session.get('selectNavName') || ''
  if (selectNavName) {
    // 判断路由名是否可访问
    selectRoute = findNodeDfs(routes, (node) => node.name == selectNavName)
  }
  return selectRoute
}

/**
 * 回显路由页面
 * @param {object} routes
 */
export function showRoute(routes) {
  let selectRouteName = ''
  let localName = session.get('selectRouteName')
  // 判断路由名是否可访问
  let selectRoute = findNodeDfs(routes, (node) => node.name == localName)
  if (selectRoute) {
    selectRouteName = selectRoute.name
  }
  if (selectRouteName) {
    store.dispatch('app/setSelectRouteName', selectRouteName)
  }
  return selectRouteName
}

/**
 * 查找路由末级页面name
 * @param {*} firstRoute
 * @returns string
 */
export function searchRouteLaster(firstRoute) {
  // 深度优先遍历查找末级页面name
  let selectNode = findNodeDfs([firstRoute], (node) => {
    return !node.hidden && (!node.children || !node.children.length)
  })
  return selectNode.name || firstRoute.name
}

/**
 * 添加全局路由
 * @param {array} routes
 * @returns
 */
export function addGlobalRoute(routes) {
  if (process.env.NODE_ENV !== 'development') {
    return [...routes]
  }
  return [...routes, ...staticRoute]
}
